from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time
from urllib.parse import urlencode
import hmac
import hashlib
import base64
import requests
APIKey="968903077273d3eacf8c9a6e47349d0e"
APISecret="Y2U1Y2MxZTljMWNhZmExNzZjOGM3MzA3"

if __name__ == '__main__':
    cur_time = datetime.now()
    date = format_date_time(mktime(cur_time.timetuple()))
    tmp = "host: " + "spark-api.xf-yun.com" + "\n"
    tmp += "date: " + date + "\n"
    tmp += "GET " + "/v1.1/chat" + " HTTP/1.1"
    tmp_sha = hmac.new(APISecret.encode('utf-8'), tmp.encode('utf-8'), digestmod=hashlib.sha256).digest()
    signature = base64.b64encode(tmp_sha).decode(encoding='utf-8')
    authorization_origin = f"api_key='{APIKey}'', algorithm='hmac-sha256', headers='host date request-line', signature='{signature}''"
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    v = {
        "authorization": authorization,  # 上方鉴权生成的authorization
        "date": date,  # 步骤1生成的date
        "host": "spark-api.xf-yun.com"  # 请求的主机名，根据具体接口替换
    }
    data={
        "header": {
            "app_id": "54ffa729"
        },
        "payload": {
            "message": {
                "text": [
                    {
                        "role": "user",
                        "content": "帮我画一座山"
                    }
                ]
            }
        }
    }
    url = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti" + urlencode(v)
    print(url)

    res=requests.post(url=url,data=data)
    print(res.text)
